import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:signage/app/data/models/devices_gruop_bean.dart';
import 'package:signage/app/modules/cast/controllers/cast_controller.dart';
import 'package:signage/app/modules/home/controllers/home_controller.dart';
import 'package:signage/app/routes/app_pages.dart';
import 'package:signage/app/services/bluetooth_service.dart';
import 'package:signage/app/utils/toast_utils.dart';
import 'package:signage/app/widgets/FocusDetector.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/custom_appbar.dart';
import 'package:signage/widgets/edit_dialog.dart';
import '../controllers/device_controller.dart';
import 'package:signage/widgets/device_list_item.dart';

class DeviceView extends GetView<DeviceController> {
  final String? source;
  const DeviceView({
    super.key,
    this.source,
  });
  @override
  Widget build(BuildContext context) {
    return Obx(
      () => FocusDetector(
          onVisibilityLost: () {
            print('🔍 onVisibilityLost');
          },
          onVisibilityGained: () {
            print('🔍 onVisibilityGained');
            if (source == 'picker') {
              // ToastUtils.show(AppLocalizations.of(context)!.translate('device_filter_hint'));
              // controller.bluetoothManager.checkPermissionAndStartScan();
            } else {
              if (Get.find<HomeController>().selectedIndex.value == 1) {
                ToastUtils.show(AppLocalizations.of(context)!
                    .translate('device_update_status'));
                controller.bluetoothManager.checkPermissionAndStartScan();
              }
            }
          },
          child: DefaultTabController(
            length: 3,
            child: Scaffold(
                backgroundColor: Color(0XFFF3F4F6),
                body: Stack(
                  children: [
                    Image.asset('assets/images/title_bar_bg.png',
                        width: Get.width),
                    Column(
                      children: [
                        CustomAppBar(
                          title: AppLocalizations.of(context)!
                              .translate('device_title'),
                          loading: false,
                          loadingRotating: FlutterBluePlus.isScanningNow,
                          onLoadingTap: () {
                            controller.bluetoothManager
                                .checkPermissionAndStartScan();
                          },
                          showBackButton: source?.isNotEmpty == true,
                          rightButtons: [
                          ],
                        ),
                        Container(
                            padding: EdgeInsets.only(left: 25.w, right: 19.w),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Expanded(
                                  child: SingleChildScrollView(
                                    scrollDirection: Axis.horizontal,
                                    child: Row(
                                      children: [
                                        ...controller.deviceGroups
                                            .map(_buildGroupChip),
                                      ],
                                    ),
                                  ),
                                ),
                                _buildAddGroupButton(context),
                              ],
                            )),
                        Expanded(
                            child: Container(
                          margin: EdgeInsets.only(
                              left: 14.w, top: 12.h, right: 14.w),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(18.r),
                                topRight: Radius.circular(18.r)),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  controller.isEdit.value
                                      ? Row(
                                          children: [
                                            16.horizontalSpace,
                                            SizedBox(
                                              width: 18.w,
                                              child: Checkbox(
                                                checkColor: Colors.black,
                                                value: controller
                                                        .selectedDevices
                                                        .length ==
                                                    controller.bluetoothManager
                                                        .deviceInfoMap.values
                                                        .where((deviceInfo) {
                                                          return deviceInfo
                                                                  .group ==
                                                              controller
                                                                  .currentGroup
                                                                  .value
                                                                  .group;
                                                        })
                                                        .toList()
                                                        .length,
                                                shape: RoundedRectangleBorder(
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            50.r)),
                                                onChanged: (value) {
                                                  if (value != null) {
                                                    if (!value) {
                                                      controller.selectedDevices
                                                          .clear();
                                                    } else {
                                                      controller.selectedDevices
                                                          .clear();
                                                      var filteredDevices =
                                                          controller
                                                              .bluetoothManager
                                                              .deviceInfoMap
                                                              .values
                                                              .where(
                                                                  (deviceInfo) {
                                                        return deviceInfo
                                                                .group ==
                                                            controller
                                                                .currentGroup
                                                                .value
                                                                .group;
                                                      }).toList();
                                                      controller.selectedDevices
                                                          .addAll(
                                                              filteredDevices);
                                                    }
                                                  }
                                                },
                                              ),
                                            ),
                                            10.horizontalSpace,
                                            Text(
                                              AppLocalizations.of(context)!
                                                  .translate(
                                                      'device_select_all'),
                                              style: TextStyle(
                                                fontSize: 16.sp,
                                                fontWeight: FontWeight.w400,
                                                letterSpacing: 0,
                                                color: Color(0XFF333333),
                                              ),
                                            ),
                                            40.horizontalSpace,
                                          ],
                                        )
                                      : TabBar(
                                          controller: controller.tabController,
                                          padding: EdgeInsets
                                              .zero, // Add padding zero
                                          tabAlignment: TabAlignment.start,
                                          labelPadding: EdgeInsets.symmetric(
                                              horizontal: 22,
                                              vertical: 0), // 调整tab之间的间距
                                          labelColor: Colors.black,
                                          unselectedLabelColor: Colors.black54,
                                          indicatorColor: Colors.transparent,
                                          indicator: null,
                                          isScrollable: true, // 修改为 true
                                          dividerHeight: 0.0,
                                          labelStyle: TextStyle(
                                            fontSize: 14.sp,
                                          ),
                                          unselectedLabelStyle: TextStyle(
                                            fontSize: 14.sp,
                                          ),
                                          tabs: [
                                            Tab(
                                                text: AppLocalizations.of(
                                                        context)!
                                                    .translate(
                                                        'device_tab_all')),
                                            Tab(
                                                text: AppLocalizations.of(
                                                        context)!
                                                    .translate(
                                                        'device_tab_online')),
                                            Tab(
                                                text: AppLocalizations.of(
                                                        context)!
                                                    .translate(
                                                        'device_tab_offline')),
                                          ],
                                        ),
                                  Spacer(),
                                  GestureDetector(
                                    onTap: () {
                                      controller.isEdit.value =
                                          !controller.isEdit.value;
                                      if (controller.isEdit.value) {
                                        controller.tabController.index = 0;
                                      } else {
                                        controller.selectedDevices.clear();
                                      }
                                    },
                                    child: controller.isEdit.value
                                        ? Text(
                                            AppLocalizations.of(context)!
                                                .translate('device_cancel'),
                                            style: TextStyle(
                                              fontSize: 14.sp,
                                              color: Color(0XFF333333),
                                            ),
                                          )
                                        : Image.asset(
                                            'assets/images/Frame@2x (8).png',
                                            width: 18.w,
                                            height: 18.h,
                                          ),
                                  ),
                                  18.horizontalSpace,
                                ],
                              ),
                              Expanded(
                                  child: TabBarView(
                                controller: controller.tabController,
                                children: [
                                  _buildDeviceList('all'),
                                  _buildDeviceList('online'),
                                  _buildDeviceList('offline'),
                                ],
                              )),
                            ],
                          ),
                        )),
                        controller.isEdit.value
                            ? Container(
                                height: 60.h,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.black.withOpacity(0.05),
                                      spreadRadius: 1,
                                      blurRadius: 1,
                                    ),
                                  ],
                                ),
                                child: SingleChildScrollView(
                                  scrollDirection: Axis.horizontal,
                                  child: Padding(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 14.w),
                                    child: Row(
                                      children: [
                                        GestureDetector(
                                          behavior: HitTestBehavior.translucent,
                                          onTap: () {
                                            controller.moveDevices();
                                          },
                                          child: Container(
                                            padding: EdgeInsets.symmetric(
                                                horizontal: 14.w),
                                            height: 40.h,
                                            decoration: BoxDecoration(
                                              color: Color(0XFFFCCF01),
                                              borderRadius:
                                                  BorderRadius.circular(28.r),
                                            ),
                                            child: Row(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                Image.asset(
                                                  'assets/images/Group 271@2x.png',
                                                  width: 18.w,
                                                  height: 18.h,
                                                ),
                                                4.horizontalSpace,
                                                Text(
                                                  AppLocalizations.of(context)!
                                                      .translate(
                                                          'device_move_to'),
                                                  style: TextStyle(
                                                    fontSize: 16.sp,
                                                    fontWeight: FontWeight.w400,
                                                    letterSpacing: 0,
                                                    color: Color(0XFF333333),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                        16.horizontalSpace,
                                        GestureDetector(
                                          behavior: HitTestBehavior.translucent,
                                          onTap: () {
                                            if (controller
                                                .selectedDevices.isEmpty) {
                                              ToastUtils.showError(
                                                  AppLocalizations.of(context)!
                                                      .translate(
                                                          'please_select_device'));
                                              return;
                                            }
                                            controller.bluetoothManager
                                                .selectDevice(
                                                    controller.selectedDevices,
                                                    source ?? '');
                                          },
                                          child: Container(
                                            padding: EdgeInsets.symmetric(
                                                horizontal: 14.w),
                                            height: 40.h,
                                            decoration: BoxDecoration(
                                              color: Color(0XFFFFFFFF),
                                              borderRadius:
                                                  BorderRadius.circular(36.r),
                                              border: Border.all(
                                                color: Color(0XFFECECECE),
                                                width: 1.0,
                                              ),
                                            ),
                                            child: Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: [
                                                Image.asset(
                                                  'assets/images/Group 1321318806@2x.png',
                                                  width: 18.w,
                                                  height: 18.h,
                                                ),
                                                4.horizontalSpace,
                                                Text(
                                                  AppLocalizations.of(context)!
                                                      .translate('cast_start'),
                                                  style: TextStyle(
                                                    fontSize: 16.sp,
                                                    fontWeight: FontWeight.w400,
                                                    letterSpacing: 0,
                                                    color: Color(0XFF333333),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                        16.horizontalSpace,
                                        GestureDetector(
                                          behavior: HitTestBehavior.translucent,
                                          onTap: () {
                                            controller.clearScreen();
                                          },
                                          child: Container(
                                            height: 40.h,
                                            child: Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: [
                                                Image.asset(
                                                  'assets/images/Group 1321318715@2x.png',
                                                  width: 18.w,
                                                  height: 18.h,
                                                ),
                                                4.horizontalSpace,
                                                Text(
                                                  AppLocalizations.of(context)!
                                                      .translate(
                                                          'device_clear_screen'),
                                                  style: TextStyle(
                                                    fontSize: 16.sp,
                                                    fontWeight: FontWeight.w400,
                                                    letterSpacing: 0,
                                                    color: Color(0XFF333333),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              )
                            : SizedBox.shrink(),
                      ],
                    ),
                    !controller.isEdit.value
                        ? Positioned(
                            bottom: 20.h,
                            right: 20.w,
                            child: FloatingActionButton(
                              heroTag: 'hero1',
                              backgroundColor: Color(0XFFFCCF01),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(100),
                              ),
                              onPressed: () {
                                _showAddDeviceDialog(context);
                              },
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(
                                    Icons.add,
                                    size: 18.w,
                                    color: Colors.black,
                                  ),
                                  2.verticalSpace,
                                  Text(
                                    AppLocalizations.of(context)!
                                        .translate('device_add'),
                                    style: TextStyle(
                                      fontSize: 12.sp,
                                      fontWeight: FontWeight.w400,
                                      letterSpacing: 0,
                                      color: Color(0XFF333333),
                                    ),
                                  ),
                                ],
                              ),
                            ))
                        : SizedBox.shrink(),
                  ],
                )),
          )),
    );
  }

  Widget _buildGroupChip(DevicesGroupBean group) {
    return Obx(
      () => Padding(
        padding: EdgeInsets.only(right: 25.w),
        child: InkWell(
          onTap: () {
            controller.changeGroup(group);
          },
          child: Column(
            children: [
              Text(
                group.groupId == '0'
                    ? AppLocalizations.of(Get.context!)!
                        .translate('device_default_group')
                    : group.group,
                style: TextStyle(
                  fontSize: 16.sp,
                  height: 26.h / 16.sp,
                  color: Color(0XFF333333),
                ),
              ),
              controller.currentGroup.value.groupId == group.groupId
                  ? Image.asset(
                      'assets/images/Vector@2x.png',
                      width: 13.w,
                      height: 5.h,
                    )
                  : SizedBox(height: 5.h)
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAddGroupButton(BuildContext context) {
    return InkWell(
      onTap: () {
        _showAddGroupDialog(context);
      },
      child: Container(
        height: 26.h,
        width: 74.w,
        decoration: BoxDecoration(
          color: Color(0XFFFAFAFA),
          borderRadius: BorderRadius.circular(4),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/images/Frame@2x.png',
              width: 18.w,
              height: 18.h,
            ),
            4.horizontalSpace,
            Text(
              AppLocalizations.of(context)!.translate('device_group'),
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w400,
                letterSpacing: 0,
                color: Color(0XFF333333),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showAddGroupDialog(BuildContext context) {
    final textController = TextEditingController();
    Get.dialog(
      EditDialog(
        title: AppLocalizations.of(context)!.translate('device_group_name'),
        hintText:
            AppLocalizations.of(context)!.translate('device_group_name_hint'),
        controller: textController,
        onConfirm: () {
          if (textController.text.isNotEmpty) {
            Get.back();
            controller.addGroup(textController.text);
          } else {
            ToastUtils.show(AppLocalizations.of(context)!
                .translate('device_group_name_hint'));
          }
        },
      ),
    );
  }

  Widget _buildDeviceList(String type) {
    return Obx(() {
      var filteredDevices =
          controller.bluetoothManager.deviceInfoMap.values.where((deviceInfo) {
        final inCurrentGroup =
            deviceInfo.groupId == controller.currentGroup.value.groupId;
        switch (type) {
          case 'online':
            return deviceInfo.canCast && inCurrentGroup;
          case 'offline':
            return !deviceInfo.canCast && inCurrentGroup;
          default:
            return inCurrentGroup;
        }
      }).toList();

      if (source == 'picker') {
        final template = Get.find<CastController>().templateModelA.value;
        print('🔍 template: ${template?.toJson()}');
        if (template != null) {
          filteredDevices = filteredDevices
              .where((device) => device.displayInfo.any((d) =>
                  d.width.toString() ==
                      template.size
                          .split('|')[1]
                          .trim()
                          .toString()
                          .split('X')[0] &&
                  d.height.toString() ==
                      template.size
                          .split('|')[1]
                          .trim()
                          .toString()
                          .split('X')[1]))
              .toList();
        }
      }

      if (source?.isNotEmpty == true) {
        final selectedDevices = Get.find<CastController>().selectedDevices;
        filteredDevices = filteredDevices
            .where((device) => selectedDevices.every((d) => d.id != device.id))
            .toList();
      }
      if (filteredDevices.isEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                'assets/images/Group 1321318735@2x.png',
                width: 232.w,
                height: 200.h,
              ),
              16.verticalSpace,
              Text(
                type == 'all'
                    ? AppLocalizations.of(Get.context!)!
                        .translate('device_no_devices')
                    : (type == 'online'
                        ? AppLocalizations.of(Get.context!)!
                            .translate('device_no_online_devices')
                        : AppLocalizations.of(Get.context!)!
                            .translate('device_no_offline_devices')),
                style: TextStyle(
                  fontSize: 15.sp,
                  color: Colors.black54,
                ),
              ),
              24.verticalSpace,
              InkWell(
                onTap: () => _showAddDeviceDialog(Get.context!),
                child: Container(
                  padding:
                      EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(252, 207, 1, 1),
                    borderRadius: BorderRadius.circular(22),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        Icons.add,
                        color: Colors.black,
                        size: 20.sp,
                      ),
                      8.horizontalSpace,
                      Text(
                        AppLocalizations.of(Get.context!)!
                            .translate('device_add_dialog_title'),
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 15.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      }

      return RefreshIndicator(
        child: ListView.builder(
          padding: EdgeInsets.zero,
          itemCount: filteredDevices.length,
          itemBuilder: (context, index) {
            final device = filteredDevices[index];
            final cachedInfo = controller.getDeviceCachedInfo(device.id);
            return Container(
              margin: EdgeInsets.only(bottom: 16.w, left: 16.w, right: 16.w),
              child: DeviceListItem(
                cachedInfo: cachedInfo,
                isSelected:
                    controller.selectedDevices.any((d) => d.id == device.id) &&
                        controller.isEdit.value,
                toggleSelection: (value) {
                  controller.selectDevice(cachedInfo!);
                },
                needToggleSelection: controller.isEdit.value,
                connectionStateStream:
                    controller.getDeviceConnectionState(device.id),
                onRemove: (id) => controller.bluetoothManager.removeDevice(id),
                onTap: () => controller.bluetoothManager
                    .selectDevice([cachedInfo!], source ?? ''),
              ),
            );
          },
        ),
        onRefresh: () async {
          await controller.bluetoothManager.checkPermissionAndStartScan();
        },
      );
    });
  }

//Get.toNamed(
  //   Routes.ADD_DEVICE,
  //   arguments: {
  //     'group': controller.currentGroup.value,
  //   },
  // );
  void _showAddDeviceDialog(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              width: Get.width,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  24.verticalSpace,
                  Text(
                    AppLocalizations.of(context)!
                        .translate('device_add_dialog_title'),
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w400,
                      letterSpacing: 0,
                      color: Color(0XFF333333),
                    ),
                  ),
                  27.verticalSpace,
                  Row(
                    children: [
                      Expanded(
                        child: InkWell(
                          onTap: () {
                            Get.back();
                            controller.scanDevice(context);
                          },
                          child: Column(
                            children: [
                              Image.asset(
                                'assets/images/Group 1321318758@2x.png',
                                width: 70.w,
                                height: 70.w,
                              ),
                              10.verticalSpace,
                              Text(
                                AppLocalizations.of(context)!
                                    .translate('device_add_bluetooth'),
                                style: TextStyle(
                                  fontSize: 15.sp,
                                  fontWeight: FontWeight.w400,
                                  letterSpacing: 0,
                                  color: Color(0XFF666666),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        child: InkWell(
                          onTap: () async {
                            Get.back();
                            controller.selectDeviceByNfc();
                          },
                          child: Column(
                            children: [
                              Image.asset(
                                'assets/images/Group 1321318762@2x.png',
                                width: 70.w,
                                height: 70.w,
                              ),
                              10.verticalSpace,
                              Text(
                                AppLocalizations.of(context)!
                                    .translate('device_add_nfc'),
                                style: TextStyle(
                                  fontSize: 15.sp,
                                  color: Color(0XFF666666),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                  70.verticalSpace,
                ],
              ),
            ));
  }
}
